package com.mindao.app.ued.service;

import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.mindao.app.common.spring.model.BaseModel;
import com.mindao.app.common.spring.service.BaseService;
import com.mindao.app.ued.model.EventPrize;
import com.mindao.app.ued.utils.ZooKeeperKeyConstants;

/**
/* 版权所有： 广州敏道科技有限公司
/*
/* 功能描述：
/*
/* 创 建 人：李国才
/* 创建时间：2016年6月25日 下午12:19:17 	
 **/
@Component ("eventPrizeService")
public class EventPrizeServiceImpl implements EventPrizeService {
	private final Logger log = LoggerFactory.getLogger(EventPrizeServiceImpl.class);
	
	@Autowired
	private BaseService baseService;
	@Autowired
	private ZooKeeperService zooKeeperService;
	
	/**
	 * 奖品个数
	 */
	private Integer prizeNumber;
	
 
	
	@Override
	public List<EventPrize> getPrizes(Long eventId) {
		// TODO Auto-generated method stub
		List<EventPrize> list= baseService.find("from EventPrize t where t.event.id=? and t.status>? order by t.sortNob", new Object[]{eventId,BaseModel.STATUS_REMOVED});
		return list;
	}
	
	/**
	 * 上下移动
	 * @param id
	 * @param id2
	 * @param b
	 */
	public boolean moveItemConf(Long id, Long parentId, boolean upside) {
		EventPrize data=(EventPrize)baseService.loadById(EventPrize.class, Long.valueOf(id));
		List<EventPrize> list= getPrizes( parentId);
		long index=1;
		for (EventPrize itemConf : list) {
			if (itemConf.getSortNob()==null || itemConf.getSortNob().longValue()!=index){
				itemConf.setSortNob(index);
				baseService.update(itemConf);
			}
			if (data.getId().equals(itemConf.getId())){
				data.setSortNob(index);
			}
			index++;
		}
		//移动
		Long sortNob= data.getSortNob();
		if (upside){
			if (sortNob>1){
				EventPrize upData =list.get(Long.valueOf(sortNob).intValue()-2);
				upData.setSortNob(sortNob);
				baseService.update(upData);
				
				data.setSortNob(sortNob-1);
				baseService.update(data);
			}
		}else{
			if (sortNob<list.size()){
				EventPrize downData =list.get(Long.valueOf(sortNob).intValue());
				downData.setSortNob(sortNob);
				baseService.update(downData);
				
				data.setSortNob(sortNob+1);
				baseService.update(data);
			}
		}
 
		return true;
	}
	@Value("${ued.prizeNumber}")
	public Integer getPrizeNumber() {
		return prizeNumber;
	}

	public void setPrizeNumber(Integer prizeNumber) {
		this.prizeNumber = prizeNumber;
		log.info("prizeNumber更新值:"+prizeNumber);
	}
	
	@PostConstruct 
	public void init(){
		log.info("prizeNumber初始值:"+prizeNumber);
		String tmps=zooKeeperService.getParaFromZookeeper(ZooKeeperKeyConstants.prizeNumber);
		if (tmps!=null){
			setPrizeNumber(Integer.valueOf(tmps));
		}
	}
	
}
